import { Button, Form, Input, message, Spin } from 'antd';
import { UserOutlined, LockOutlined, VerifiedOutlined } from '@ant-design/icons';
import styles from './index.module.scss';
import { rules } from './rules';
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import { setCache } from '@/utils/storage';
import { TLogin } from '@/api/login/login.type';
import Captcha from "react-captcha-code";
import { useRootStore } from '@/store';
import { dealRouteData } from '@/router/deal';
import { login, remoteUserAuth } from '@/api/login';

const LoginForm = () => {
    let { user, permissions } = useRootStore();
    let navigate = useNavigate();
    let [code, setCode] = useState<string>('');
    const [loading, setLoading] = useState<boolean>(false);

    const onFinish = async (values: TLogin) => {
        user.setUserToken('');
        setCache('token', '');
        setLoading(true);
        try {
            let res = await login(values);
            let { token, userInfo } = res.data;
            user.setUserToken(token);
            user.setUserInfo(userInfo);
            setCache('token', token);
            let authResult = await remoteUserAuth();
            if (authResult.data.length == 0) {
                message.error('无访问权限');
                return false;
            }
            let result = dealRouteData(authResult.data);
            let { buttonPermissions, menuRouter, paveRouters, homeRoute } = result;
            permissions.init(buttonPermissions, menuRouter, paveRouters, homeRoute);
            message.success("登录成功")
            navigate(homeRoute.redirect || homeRoute.path);
            return Promise.resolve();
        } finally {
            setLoading(false);
            return Promise.resolve();
        }
    };
    const onFinishFailed = async () => {
        return Promise.reject('请完善信息')
    };
    //验证码切换
    const codeChange = (value: string) => {
        setCode(value)
    }

    return (
        <Spin spinning={loading}>
            <div className={`${styles.form_wrapper} flex-row`}>
                <div className={`${styles.form_side}`}>
                    <h2 className={styles.name}>Nest管理平台</h2>
                </div>
                <div className={`${styles.form_main} flex-col`}>
                    <h3 className={styles.welcome}>欢迎登录</h3>
                    <Form
                        name="basic"
                        style={{ width: '100%' }}
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item
                            label=""
                            name="username"
                            rules={rules.username}
                        >
                            <Input addonBefore={<UserOutlined />} size="large" placeholder='请输入账号' />
                        </Form.Item>

                        <Form.Item
                            label=""
                            name="password"
                            rules={rules.password}
                        >
                            <Input.Password addonBefore={<LockOutlined />} autoComplete="off" size="large" placeholder='请输入密码' />
                        </Form.Item>
                        <div className='flex-row'>
                            <div className='flex-item'>
                                <Form.Item
                                    label=""
                                    name="usercode"
                                    rules={[
                                        { required: true, message: '请输入验证码！' },
                                        {
                                            validator(_rule, value, callback) {
                                                if (!value) {
                                                    callback();
                                                } else if (value != code) {
                                                    callback('验证码不正确');
                                                } else {
                                                    callback();
                                                }
                                            },
                                        }
                                    ]}
                                >
                                    <Input addonBefore={<VerifiedOutlined />} size="large" placeholder='请输入验证码' />
                                </Form.Item>
                            </div>
                            <div className={styles.code}>
                                <Captcha className={styles.captcha} bgColor={'#f2f2f2'} width={120} onChange={codeChange} />
                            </div>
                        </div>
                        <Form.Item >
                            <Button type="primary" style={{ width: '100%' }} size='large' htmlType="submit">登 录</Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </Spin>
    )
};

export default LoginForm